
package com.sophie.util;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.CannedAccessControlList;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;

import java.io.File;

/**
 * @Author: Rowena
 * @CreateTime: 2024-09-02 10:22:57
 * @Version: 1.0
 */

public class QCloudUtil {
    private static final  String secretId ="AKIDCE1bGj4NeptrpleNtGTTHtPgo10wlMjx";
    private static final   String secretKey ="OYUAamovvoVxAA0ax71kT8dxHZeebYRC";
    //存储桶名称
    public static final String bucketName="love-you-1329179294";
    public static final String regionName="ap-shanghai";

    //参数1：文件名称  参数2：你的真实磁盘文件路径
    public static void upload(String fileKey,String filePath){
        //1.设置访问密钥
        BasicCOSCredentials credentials=new BasicCOSCredentials(secretId,secretKey);
        //2.设置存储桶地狱
        Region region=new Region(regionName);
        //3.创建存储桶客户端
        ClientConfig clientConfig =new ClientConfig(region);
        clientConfig.setHttpProtocol(HttpProtocol.https);
        COSClient cosClient = new COSClient(credentials,clientConfig);
        //6.创建File对象
        File localFile =new File(filePath);
        //上传文件到存储桶
        PutObjectRequest putObjectRequest =new PutObjectRequest(bucketName,fileKey,localFile);
        //设置存储桶的权限
        putObjectRequest.setCannedAcl(CannedAccessControlList.PublicRead);
        PutObjectResult result = cosClient.putObject(putObjectRequest);
        System.out.println(result);
        System.out.println("文件上传成功!");
        //关闭存储桶客户端
        cosClient.shutdown();
    }
}
